"""
数据分析相关的数据模型定义
"""
from datetime import datetime, date
from typing import List, Dict, Any, Optional, Union
from pydantic import BaseModel, Field, validator
from enum import Enum
import numpy as np


class TimeGranularity(str, Enum):
    """时间粒度枚举"""
    MINUTE = "minute"
    HOUR = "hour"
    DAY = "day"
    WEEK = "week"
    MONTH = "month"
    YEAR = "year"


class ChartType(str, Enum):
    """图表类型枚举"""
    LINE = "line"
    BAR = "bar"
    PIE = "pie"
    AREA = "area"
    SCATTER = "scatter"
    HEATMAP = "heatmap"
    HISTOGRAM = "histogram"
    BOX_PLOT = "box_plot"


class AggregationType(str, Enum):
    """聚合类型枚举"""
    COUNT = "count"
    SUM = "sum"
    AVERAGE = "average"
    MIN = "min"
    MAX = "max"
    MEDIAN = "median"
    PERCENTILE = "percentile"


class ReportType(str, Enum):
    """报告类型枚举"""
    DAILY = "daily"
    WEEKLY = "weekly"
    MONTHLY = "monthly"
    CUSTOM = "custom"
    INCIDENT = "incident"
    PERFORMANCE = "performance"


class DataPoint(BaseModel):
    """数据点模型"""
    timestamp: datetime = Field(..., description="时间戳")
    value: Union[int, float] = Field(..., description="数值")
    label: Optional[str] = Field(None, description="标签")
    metadata: Optional[Dict[str, Any]] = Field(None, description="元数据")

    model_config = {
        "json_schema_extra": {
            "example": {
                "timestamp": "2024-01-01T12:00:00Z",
                "value": 25,
                "label": "人员数量",
                "metadata": {"camera_id": "cam_001", "zone": "entrance"}
            }}
            }


class TimeSeries(BaseModel):
    """时间序列模型"""
    series_id: str = Field(..., description="序列ID")
    name: str = Field(..., description="序列名称")
    description: Optional[str] = Field(None, description="描述")
    unit: Optional[str] = Field(None, description="单位")
    data_points: List[DataPoint] = Field(..., description="数据点列表")
    granularity: TimeGranularity = Field(..., description="时间粒度")
    start_time: datetime = Field(..., description="开始时间")
    end_time: datetime = Field(..., description="结束时间")

    model_config = {"json_schema_extra": {
            "example": {
                "series_id": "person_count_series",
                "name": "人员数量统计",
                "description": "每小时人员数量变化",
                "unit": "人",
                "data_points": [],
                "granularity": "hour",
                "start_time": "2024-01-01T00:00:00Z",
                "end_time": "2024-01-01T23:59:59Z"
        }
    }
        }


class StatisticalSummary(BaseModel):
    """统计摘要模型"""
    count: int = Field(..., description="数据点数量")
    sum: float = Field(..., description="总和")
    mean: float = Field(..., description="平均值")
    median: float = Field(..., description="中位数")
    std: float = Field(..., description="标准差")
    min: float = Field(..., description="最小值")
    max: float = Field(..., description="最大值")
    percentile_25: float = Field(..., description="25%分位数")
    percentile_75: float = Field(..., description="75%分位数")

    model_config = {
        "json_schema_extra": {
            "example": {
                "count": 100,
                "sum": 2500.0,
                "mean": 25.0,
                "median": 24.0,
                "std": 5.2,
                "min": 10.0,
                "max": 45.0,
                "percentile_25": 20.0,
                "percentile_75": 30.0
            }
        }}


class HeatmapData(BaseModel):
    """热力图数据模型"""
    heatmap_id: str = Field(..., description="热力图ID")
    camera_id: str = Field(..., description="摄像头ID")
    timestamp: datetime = Field(..., description="时间戳")
    grid_size: int = Field(..., description="网格大小")
    width: int = Field(..., description="图像宽度")
    height: int = Field(..., description="图像高度")
    data: List[List[float]] = Field(..., description="热力图数据矩阵")
    max_value: float = Field(..., description="最大值")
    min_value: float = Field(..., description="最小值")
    hotspots: List[Dict[str, Any]] = Field([], description="热点区域")

    model_config = {"json_schema_extra": {
            "example": {
                "heatmap_id": "heatmap_001",
                "camera_id": "cam_001",
                "timestamp": "2024-01-01T12:00:00Z",
                "grid_size": 20,
                "width": 640,
                "height": 480,
                "data": [[0.1, 0.2], [0.3, 0.4]],
                "max_value": 1.0,
                "min_value": 0.0,
                "hotspots": []
        }
    }
        }


class TrendAnalysis(BaseModel):
    """趋势分析模型"""
    analysis_id: str = Field(..., description="分析ID")
    series_id: str = Field(..., description="序列ID")
    trend_direction: str = Field(..., description="趋势方向")
    trend_strength: float = Field(..., ge=0, le=1, description="趋势强度")
    slope: float = Field(..., description="斜率")
    r_squared: float = Field(..., ge=0, le=1, description="R平方值")
    seasonal_pattern: Optional[Dict[str, Any]] = Field(None, description="季节性模式")
    anomalies: List[Dict[str, Any]] = Field([], description="异常点")
    forecast: List[DataPoint] = Field([], description="预测数据")
    confidence_interval: Optional[Dict[str, List[float]]] = Field(None, description="置信区间")

    model_config = {
        "json_schema_extra": {
            "example": {
                "analysis_id": "trend_001",
                "series_id": "person_count_series",
                "trend_direction": "increasing",
                "trend_strength": 0.75,
                "slope": 0.5,
                "r_squared": 0.85,
                "seasonal_pattern": {"daily": True, "weekly": False},
                "anomalies": [],
                "forecast": [],
                "confidence_interval": {"upper": [30, 32, 34], "lower": [20, 22, 24]}}
            }
        }


class ChartConfig(BaseModel):
    """图表配置模型"""
    chart_type: ChartType = Field(..., description="图表类型")
    title: str = Field(..., description="图表标题")
    x_axis_label: Optional[str] = Field(None, description="X轴标签")
    y_axis_label: Optional[str] = Field(None, description="Y轴标签")
    width: int = Field(800, description="图表宽度")
    height: int = Field(600, description="图表高度")
    colors: Optional[List[str]] = Field(None, description="颜色配置")
    show_legend: bool = Field(True, description="是否显示图例")
    show_grid: bool = Field(True, description="是否显示网格")
    interactive: bool = Field(True, description="是否交互式")

    model_config = {
        "json_schema_extra": {
            "example": {
                "chart_type": "line",
                "title": "人员数量趋势",
                "x_axis_label": "时间",
                "y_axis_label": "人数",
                "width": 800,
                "height": 600,
                "colors": ["#1f77b4", "#ff7f0e"],
                "show_legend": True,
                "show_grid": True,
                "interactive": True
            }
        }}


class ChartData(BaseModel):
    """图表数据模型"""
    chart_id: str = Field(..., description="图表ID")
    config: ChartConfig = Field(..., description="图表配置")
    series: List[TimeSeries] = Field(..., description="数据序列")
    created_at: datetime = Field(..., description="创建时间")
    updated_at: datetime = Field(..., description="更新时间")

    model_config = {"json_schema_extra": {
            "example": {
                "chart_id": "chart_001",
                "config": {},
                "series": [],
                "created_at": "2024-01-01T12:00:00Z",
                "updated_at": "2024-01-01T12:00:00Z"
            }}
        }


class ReportSection(BaseModel):
    """报告章节模型"""
    section_id: str = Field(..., description="章节ID")
    title: str = Field(..., description="章节标题")
    content: str = Field(..., description="章节内容")
    charts: List[str] = Field([], description="图表ID列表")
    tables: List[Dict[str, Any]] = Field([], description="表格数据")
    order: int = Field(..., description="排序")

    model_config = {
        "json_schema_extra": {
            "example": {
                "section_id": "section_001",
                "title": "人流量统计",
                "content": "本章节分析了过去一周的人流量变化趋势...",
                "charts": ["chart_001", "chart_002"],
                "tables": [],
                "order": 1
            }
        }}


class Report(BaseModel):
    """报告模型"""
    report_id: str = Field(..., description="报告ID")
    title: str = Field(..., description="报告标题")
    report_type: ReportType = Field(..., description="报告类型")
    description: Optional[str] = Field(None, description="报告描述")
    sections: List[ReportSection] = Field(..., description="报告章节")
    summary: Optional[str] = Field(None, description="报告摘要")
    insights: List[str] = Field([], description="数据洞察")
    recommendations: List[str] = Field([], description="建议")
    period_start: datetime = Field(..., description="统计开始时间")
    period_end: datetime = Field(..., description="统计结束时间")
    generated_at: datetime = Field(..., description="生成时间")
    generated_by: str = Field(..., description="生成者")

    model_config = {"json_schema_extra": {
            "example": {
                "report_id": "report_001",
                "title": "每日人流量分析报告",
                "report_type": "daily",
                "description": "分析校园各区域的人流量变化",
                "sections": [],
                "summary": "今日总人流量较昨日增长15%...",
                "insights": ["入口区域在上午9-10点达到峰值"],
                "recommendations": ["建议在高峰期增加引导人员"],
                "period_start": "2024-01-01T00:00:00Z",
                "period_end": "2024-01-01T23:59:59Z",
                "generated_at": "2024-01-02T08:00:00Z",
                "generated_by": "system"
        }
    }
        }


class DataQuery(BaseModel):
    """数据查询模型"""
    query_id: str = Field(..., description="查询ID")
    data_source: str = Field(..., description="数据源")
    filters: Dict[str, Any] = Field({}, description="过滤条件")
    aggregation: Optional[AggregationType] = Field(None, description="聚合类型")
    group_by: Optional[List[str]] = Field(None, description="分组字段")
    time_range: Dict[str, datetime] = Field(..., description="时间范围")
    granularity: TimeGranularity = Field(..., description="时间粒度")
    limit: Optional[int] = Field(None, description="结果限制")

    model_config = {
        "json_schema_extra": {
            "example": {
                "query_id": "query_001",
                "data_source": "person_detection",
                "filters": {"camera_id": "cam_001"},
                "aggregation": "count",
                "group_by": ["camera_id", "zone_id"],
                "time_range": {
                "start": "2024-01-01T00:00:00Z",
                "end": "2024-01-01T23:59:59Z"
                }},
                "granularity": "hour",
                "limit": 1000
            }
        }


class ExportConfig(BaseModel):
    """导出配置模型"""
    format: str = Field(..., description="导出格式")
    include_charts: bool = Field(True, description="是否包含图表")
    include_raw_data: bool = Field(False, description="是否包含原始数据")
    compression: Optional[str] = Field(None, description="压缩格式")
    password_protected: bool = Field(False, description="是否密码保护")

    model_config = {
        "json_schema_extra": {
            "example": {
                "format": "pdf",
                "include_charts": True,
                "include_raw_data": False,
                "compression": "zip",
                "password_protected": False
            }
        }}


class Dashboard(BaseModel):
    """仪表板模型"""
    dashboard_id: str = Field(..., description="仪表板ID")
    name: str = Field(..., description="仪表板名称")
    description: Optional[str] = Field(None, description="描述")
    layout: Dict[str, Any] = Field(..., description="布局配置")
    widgets: List[Dict[str, Any]] = Field(..., description="组件列表")
    refresh_interval: int = Field(30, description="刷新间隔(秒)")
    is_public: bool = Field(False, description="是否公开")
    created_by: str = Field(..., description="创建者")
    created_at: datetime = Field(..., description="创建时间")
    updated_at: datetime = Field(..., description="更新时间")

    model_config = {"json_schema_extra": {
            "example": {
                "dashboard_id": "dashboard_001",
                "name": "实时监控仪表板",
                "description": "显示实时人流量和安全状态",
                "layout": {"columns": 3, "rows": 2},
                "widgets": [
                    {
                        "id": "widget_001",
                        "type": "chart",
                        "position": {"x": 0, "y": 0, "w": 2, "h": 1},
                        "config": {"chart_id": "chart_001"}
                    }
                ],
                "refresh_interval": 30,
                "is_public": False,
                "created_by": "admin",
                "created_at": "2024-01-01T12:00:00Z",
                "updated_at": "2024-01-01T12:00:00Z"
            }
        }}


class AlertThreshold(BaseModel):
    """告警阈值模型"""
    threshold_id: str = Field(..., description="阈值ID")
    metric_name: str = Field(..., description="指标名称")
    operator: str = Field(..., description="操作符")
    value: float = Field(..., description="阈值")
    severity: str = Field(..., description="严重程度")
    enabled: bool = Field(True, description="是否启用")

    model_config = {
        "json_schema_extra": {
            "example": {
                "threshold_id": "threshold_001",
                "metric_name": "person_count",
                "operator": ">",
                "value": 50.0,
                "severity": "warning",
                "enabled": True
            }
        }}


class PerformanceMetrics(BaseModel):
    """性能指标模型"""
    metric_id: str = Field(..., description="指标ID")
    name: str = Field(..., description="指标名称")
    value: float = Field(..., description="指标值")
    unit: Optional[str] = Field(None, description="单位")
    timestamp: datetime = Field(..., description="时间戳")
    tags: Dict[str, str] = Field({}, description="标签")

    model_config = {"json_schema_extra": {
            "example": {
                "metric_id": "metric_001",
                "name": "detection_accuracy",
                "value": 0.95,
                "unit": "percentage",
                "timestamp": "2024-01-01T12:00:00Z",
                "tags": {"model": "yolov8", "camera": "cam_001"}
            }}
        }